﻿<%@ Control Language="VB" AutoEventWireup="false" CodeFile="Edit.ascx.vb" Inherits="Control_BanHang_Edit" %>
<script type="text/javascript">
    function ajaxJquery() {

        $(function () {


            // Get Detail Order
            var surl = '<%=ResolveUrl("~/Page/OrderDetailJson.ashx")%>';
            surl += "?OrderId=" + $("#<%= hidID.ClientID %>").val();
            $.ajax({
                url: surl,
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) {
                    return data;
                },
                success: function (data) {
                    if (data.OrderDetails.OrderDetail != null) {
                        if (data.OrderDetails.OrderDetail.length != null) {

                            //Chi tiet don hang co nhieu hon 1 item
                            if (data.OrderDetails.OrderDetail.length > 0) {
                                for (i = 0; i < data.OrderDetails.OrderDetail.length; i++) {
                                    $("#tableChoices").append(RowDetailOrder(i, data.OrderDetails.OrderDetail[i]));
                                    //nghiavt sau khi return str --> settype for nubmer va
                                    SetTypeforNumber(i);
                                    // ListenEnterOnForm();
                                }
                                $("#<%= hidRowIndex.ClientId %>").val(data.OrderDetails.OrderDetail.length);
                            }
                        }
                        else {
                            //Chi tiet don hang co 1 item           
                            var ctrlId = 0;
                            $("#tableChoices").append(RowDetailOrder(0, data.OrderDetails.OrderDetail));
                            SetTypeforNumber(ctrlId);
                            $("#<%= hidRowIndex.ClientId %>").val(1);
                        }
                        SetAutoComplete();
                        // ListenEnterOnForm();
                    }
                    else {
                        $("#<%=hidSale_Unit.ClientId %>").val(2);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //Alertbox("Error")
                }
                //LANG NGHE ENTER
                //  ListenEnterOnForm();

            });


            //                });
            //            }
            //  

            // register thickbox after postback
            var isAsyncPostback = Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();
            if (isAsyncPostback) {
                tb_init('a.thickbox, area.thickbox, input.thickbox');
            }

            $("#OriginalDeliveryDate").val($("#<%=txtOrderDate.ClientID %>").val());

            $("#<%= chkEditDelivery.ClientID %>").click(function () {

                if ($(this).attr('checked') == true) {
                    $("#<%=txtOrderDate.ClientID %>").attr("disabled", false);
                    $("#<%=txtOrderDate.ClientID %>").removeClass("aspNetDisabled");
                    $("#<%=txtOrderDate.ClientID %>").datepicker({ dateFormat: 'dd/mm/yy' });
                }
                else {
                    $("#<%=txtOrderDate.ClientID %>").attr("disabled", true);
                    $("#<%=txtOrderDate.ClientID %>").addClass("aspNetDisabled");
                    $("#<%=txtOrderDate.ClientID %>").val($("#OriginalDeliveryDate").val());
                }

            });


            $("#btnSave").click(function () {

                if ($("#<%= ddlStore.ClientID %>").val() == "") {
                    Alertbox("Hãy chọn cửa hàng");
                    return false;

                }
                if ($("#<%= txtMaDonHang.ClientID %>").val() == "") {
                    Alertbox("Hãy nhập mã đơn hàng");
                    return false;

                }

                if ($("#<%= txtCustomerCode.ClientID %>").val() == "") {
                    Alertbox("Hãy nhập tên khách hàng");
                    return false;

                }

                $("#<%= btnSaveOrderDetail.ClientID %>").click();
                //return false;


            });


        });
    }

    function showRowIndexs() {
        var i = 0;
        $("#tableChoices tr td.tdLabel").each(function () {
            i++;
            $(this).html(i + ".");
        });

    }

    // Thêm 1 dòng sản phẩm mới để nhập
    function addFormField() {
        var ctrlId = $("#<%= hidRowIndex.ClientID %>").val();
        $("#tableChoices").append("<tr class='row' id='pRow" + ctrlId + "'><td width='20px' class='tdLabel'>" + (ctrlId * 10) + ".</td><td width='130px'><input  class='TextBoxInPut' type='text' name='txtChoice" + ctrlId + "' id='txtChoice" + ctrlId + "' style = 'width: 130px' onblur='SetOnBlurMaterial(" + ctrlId + ")' /></td><td><span id = 'spName" + ctrlId + "'></span></td><td> <input class='TextBox' type='text' name='txtAmount" + ctrlId + "' id='txtAmount" + ctrlId + "' onblur='CheckValuePress(" + ctrlId + ")' style='width: 70px; text-align: right' value = '0' maxlength='9'/></td><td nowrap ='nowrap' align = 'right'>&nbsp;&nbsp;<a id = 'hplSel" + ctrlId + "'  href = 'javascript:SelectProduct(" + ctrlId + ")'>Chọn</a>&nbsp;-&nbsp;<a href='#' onClick='removeFormField(\"#pRow" + ctrlId + "\"); return false;'>Xóa</a><input type='text' name='hidAmount" + ctrlId + "' id='hidAmount" + ctrlId + "' value = '0' style = 'width: 1px; display: none' /></td></tr>");
        // CreateOption(ctrlId);
        // SetTypeforNumber(ctrlId);
        $("#<%= hidRowIndex.ClientID %>").val(++ctrlId);

        showRowIndexs();

        SetAutoComplete();

        $("#<%= divChoices.ClientID %> #tableChoices input").focus(function () {
            $("#curId").val(this.id);
        });
    }

    // Xet chi cho go cac phim so tren ban phim
    function SetTypeforNumber(sIndex) {
        $("#txtAmount" + sIndex).keydown(function (event) {
            // Allow: backspace, delete, tab and escape
            if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
            // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) ||
            // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
            }
        });
    }

    function removeFormField(id) {

        var indexRow = eval(id.substring(5, id.length));
        var cId = $("input:hidden", id).val();
        var data = "{'cID':'" + cId + "'}"; //create the JSON data to send to server
        if (cId > 0) //call the Page method using JQuery ajax 
        {
            $.ajax(
            {
                type: "POST",
                url: "Edit.aspx/DeletePollChoice",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        }
        $(id).remove();
        var index = $("#<%=hidRowIndex.ClientId %>");

        // Nếu dòng chọn xóa  nằm trc dòng cuối cùng
        if (indexRow + 1 < index.val()) {
            for (i = indexRow + 1; i < index.val(); i++) {
                // Lấy index dòng mới
                var ctrlId = i - 1;
                // Nếu là dòng đã có dự liệu thì giữ lấy lai giá tri cũ trc khi xóa
                if ($("#txtChoice" + i).val() != "" || $("#txtAmount" + i).val() != "" || eval(("#txtAmount" + i).val()) > 0) {

                    //  var promotion = $("#Promotion" + i).val();
                    var materialCode = $("#txtChoice" + i).val();
                    var materialName = $("#spName" + i).text();
                    var amount = $("#txtAmount" + i).val();
                    //  var PcsOnCTN = $("#spQuyDoi" + i).html();
                    var sAmount = $("#spGrossAmount" + i).text();
                    var hidGrossAmount = $("#hidAmount" + i).val();


                    // xóa dòng cũ
                    $("#pRow" + i).remove();

                    $("#tableChoices").append("<tr class='row' id='pRow" + ctrlId + "'><td width='20px' class='tdLabel'>" + (ctrlId) + ".</td><td width='130px'><input class='TextBoxInPut' type='text' name='txtChoice" + ctrlId + "' id='txtChoice" + ctrlId + "' style = 'width: 130px' onblur='SetOnBlurMaterial(" + ctrlId + ")' value='" + materialCode + "' /></td><td><span id = 'spName" + ctrlId + "'>" + materialName + "</span></td><td><input class='TextBox' type='text' name='txtAmount" + ctrlId + "' id='txtAmount" + ctrlId + "' onblur='CheckValuePress(" + ctrlId + ")' style='width: 70px; text-align: right' value = '" + amount + "' maxlength='9'/></td><td nowrap ='nowrap' align = 'right'>&nbsp;&nbsp;<a id = 'hplSel" + ctrlId + "'  href = 'javascript:SelectProduct(" + ctrlId + ")'>Chọn</a>&nbsp;-&nbsp;<a href='#' onClick='removeFormField(\"#pRow" + ctrlId + "\"); return false;'>Xóa</a><input type='text' name='hidAmount" + ctrlId + "' id='hidAmount" + ctrlId + "' value = '0' style = 'width: 1px; display: none' /></td></tr>");

                    SetTypeforNumber(ctrlId);
                }
                else {
                    $("#pRow" + i).remove();

                    $("#tableChoices").append("<tr class='row' id='pRow" + ctrlId + "'><td width='20px' class='tdLabel'>" + (ctrlId) + ".</td><td ><input  class='TextBoxInPut' type='text' name='txtChoice" + ctrlId + "' id='txtChoice" + ctrlId + "' style = 'width: 130px' onblur='SetOnBlurMaterial(" + ctrlId + ")' /></td><td><span id = 'spName" + ctrlId + "'></span></td><td> <input class='TextBox' type='text' name='txtAmount" + ctrlId + "' id='txtAmount" + ctrlId + "' onblur='CheckValuePress(" + ctrlId + ")' style='width: 70px; text-align: right' value = '0' maxlength='9'/></td><td nowrap ='nowrap' align = 'right'>&nbsp;&nbsp;<a id = 'hplSel" + ctrlId + "'  href = 'javascript:SelectProduct(" + ctrlId + ")'>Chọn</a>&nbsp;-&nbsp;<a href='#' onClick='removeFormField(\"#pRow" + ctrlId + "\"); return false;'>Xóa</a><input type='text' name='hidAmount" + ctrlId + "' id='hidAmount" + ctrlId + "' value = '0' style = 'width: 1px; display: none' /></td></tr>");


                    // CreateOption(ctrlId);

                    SetTypeforNumber(ctrlId);
                }
            }
            SetAutoComplete();
        }

        //ga'n lai index khi remove
        index.val(index.val() - 1);

        showRowIndexs();
        //GetTotalGrossAmount();
    }



    function SetAutoComplete() {
        $(".TextBoxInPut").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Services/wsAutoComplete.asmx/GetListAutoCompleteProduct")%>',
                    data: "{ 'strSrc': '" + request.term.trim() + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) {
                        return data;
                    },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            $("#<%=txtmaterialCode.ClientId %>").val('');
                            return {
                                value: item
                            }
                        }))
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //Alertbox(textStatus);
                    }
                });
            },
            minLength: 1
        });

        $('input').live("keypress", function (e) {
            /* ENTER PRESSED*/
            if (e.keyCode == 13) {
                /* FOCUS ELEMENT */
                var inputs = $(this).parents("form").eq(0).find(":input");
                var idx = inputs.index(this);

                //hard code for edit
                if ((idx - 25) % 3 == 1) {
                    inputs[idx + 2].focus();
                    inputs[idx + 2].select();
                } else {

                    inputs[idx + 1].focus(); //  handles submit buttons
                    inputs[idx + 1].select();
                }
                return false;
            }
        });

    }

    //Set lai gia tri khi nguoi dung chon san pham bang chuc nang AutoComplete
    function SetOnBlurMaterial(sIndexName) {
        var sMaterialName = $("#txtChoice" + sIndexName).val();
        if (sMaterialName != "") {
            if (sMaterialName.indexOf(" - ") != -1) {
                var arrMaterial = sMaterialName.split(" - ");
                $("#spName" + sIndexName).html(arrMaterial[1]);
                $("#txtChoice" + sIndexName).val(arrMaterial[0]);

                /*if (sMaterialName.substring(9, sMaterialName.lengh) != "") {
                $("#spName" + sIndexName).html(sMaterialName.substring(9, sMaterialName.lengh));
                }*/
            }
            else
                $("#txtChoice" + sIndexName).val(sMaterialName.substring(0, 8));
            $("#txtAmount" + sIndexName).select();
            //  GetAmountItem(sMaterialName.substring(0, 6), $("#txtAmount" + sIndexName).val(), $("#ddlUnit" + sIndexName).val(), sIndexName);
        }

    }

    function SelectProduct(item) {
        $("#<%=hplShowProduct.ClientId %>").attr("href", "../Banhang/Popup.aspx?item=" + item + "&keepThis=true&TB_iframe=true&height=420&width=500&modal=true");
        $("#<%=hplShowProduct.ClientId %>").click();
    }

    function setProductValue(MaterialCode, MaterialName, item) {
        $("#txtChoice" + item).val(MaterialCode);
        $("#spName" + item).html(MaterialName);
        $("#txtAmount" + item).select();

        // GetAmountItem(MaterialCode, $("#txtAmount" + item).val(), $("#ddlUnit" + item).val(), item);
    }
    function GenerateOrderId() {
        //neu chon --chon-- 
        if ($("#<%= ddlStore.ClientId %>").val() == "") {
            $("#<%=txtMaDonHang.ClientId %>").val("");
            return false;
        }
        $.ajax({
            url: '<%=ResolveUrl("~/Services/wsAutoComplete.asmx/GenerateOrderNumber")%>',
            data: "{ 'sSACode': '" + $("#<%= ddlStore.ClientId %>").val() + "' }",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) {
                return data;
            },
            success: function (data) {
                if (data.d != "") {
                    $("#<%=txtMaDonHang.ClientId %>").val(data.d);
                    return false;
                }
                else {
                    return false;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //Alertbox(textStatus);
            }
        });
    }

    //nghiavt bug cho nay
    //Show chi tiet don hang
    function RowDetailOrder(ctrlId, objDetail) {


        var str = "<tr class='row' id='pRow" + ctrlId + "'><td width='20px' class='tdLabel'>" + (ctrlId + 1) + ".</td><td width='130px'><input class='TextBoxInPut' type='text' name='txtChoice" + ctrlId + "' id='txtChoice" + ctrlId + "' style = 'width: 130px' onblur='SetOnBlurMaterial(" + ctrlId + ")' value='" + objDetail.Code + "' /></td><td><span id = 'spName" + ctrlId + "'>" + objDetail.Title + "</span></td><td><input class='TextBox' type='text' name='txtAmount" + ctrlId + "' id='txtAmount" + ctrlId + "' onblur='CheckValuePress(" + ctrlId + ")' style='width: 70px; text-align: right' value = '" + objDetail.Number + "' maxlength='9'/></td><td nowrap ='nowrap' align = 'right'>&nbsp;&nbsp;<a id = 'hplSel" + ctrlId + "'  href = 'javascript:SelectProduct(" + ctrlId + ")'>Chọn</a>&nbsp;-&nbsp;<a href='#' onClick='removeFormField(\"#pRow" + ctrlId + "\"); return false;'>Xóa</a><input type='text' name='hidAmount" + ctrlId + "' id='hidAmount" + ctrlId + "' value = '0' style = 'width: 1px; display: none' /></td></tr>";


        return str;
    }



</script>

<asp:UpdatePanel ID="uplOrder" runat="server">
<ContentTemplate>
<div  class="BoxField">   
    <div  class="HeadTitle">
	    <h3><asp:Label ID="Label5"  runat="server" Text="CHỈNH SỬA ĐƠN HÀNG " /></h3>
    </div>
    <div class="DivRequired">
          <span class="fieldRequired">&nbsp;</span>Trường yêu cầu nhập dữ liệu
    </div>
    <div class="Error">
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="#FF3300" />        
    </div>

    <div style="clear: both">
    </div>

    <div class="DivRow">
	    <div  class="DivLabel">
		    <asp:Label ID="Label6" CssClass="TextLabel" runat="server" Text="Cửa hàng:" /><span class="fieldRequired"></span>
	    </div>
	    <div style="width: 32%; float: left">
		    <asp:DropDownList ID = "ddlStore" CssClass = "DropDownList" runat="server"/>      
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" Display="None" ErrorMessage="Hãy chọn Cửa hàng" ControlToValidate="ddlStore" SetFocusOnError="true"/>
          
	    </div>
        <div style="width: 6%; float: left;padding-left:5px;">
            <asp:Label ID="Label8" runat="server" Text="Giá trị:" CssClass="TextLabel" />
        </div>
        <div style="width: 20%; float: left">
          <asp:Label ID="lblGrossAmount" CssClass="TextLabel" runat="server" Text="0" />
        </div>
	</div>
    <div style="clear: both"></div>
    <div class="DivRow">
	    <div  class="DivLabel">
		    <asp:Label ID="lblDoc_serial_no" CssClass="TextLabel" runat="server" Text="Mã đơn hàng:" /><span class="fieldRequired"></span>
	    </div>
	    <div  class="DivTextBox" >
		    <asp:TextBox ID="txtMaDonHang" CssClass="TextBox" runat="server" Text="" Enabled="True" MaxLength="17" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="None" ErrorMessage="Hãy nhập Mã đơn hàng" ControlToValidate="txtMaDonHang" SetFocusOnError="true"/>
	    </div>
	</div>
       
    <div class="DivRow">
	<div  class="DivLabel">
		<asp:Label ID="Label1" CssClass="TextLabel" runat="server" Text="Tên khách hàng :" /><span class="fieldRequired"></span>
	</div>
	<div  class="DivTextBox" >
        <asp:TextBox ID = "txtCustomerCode" CssClass = "TextBox" runat="server" />&nbsp;
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Hãy nhập tên khách hàng" Display="None" ControlToValidate="txtCustomerCode" SetFocusOnError="true"></asp:RequiredFieldValidator>
	</div>
	</div>
	
    <div class="DivRow">
	    <div  class="DivLabel">
		    <asp:Label ID="Label9" CssClass="TextLabel" runat="server" Text="Địa chỉ:" />
	    </div>
	    <div  class="DivTextBox" >
            <asp:TextBox ID = "txtAddress" runat="server" Text = "" CssClass="TextBox"/>            
	    </div>
	</div>

    <div class="DivRow">
	    <div  class="DivLabel">
		    <asp:Label ID="Label7" CssClass="TextLabel" runat="server" Text="Điện thoại:" />
	    </div>
	    <div  class="DivTextBox" >
           <asp:TextBox ID = "txtPhone" runat="server" Text = "" CssClass="TextBox"/>            
	    </div>
	</div>
    

    <div class="DivRow" id="DivShipTo">
	<div  class="DivLabel">
		<asp:Label ID="Label4" CssClass="TextLabel" runat="server" Text="Email:" />
	</div>
	<div  class="DivTextBox">
        <asp:TextBox ID = "txtEmail" runat="server" Text = "" CssClass="TextBox"/>   
	</div>
	</div>

    <div class="DivRow">
	<div  class="DivLabel">
		<asp:Label ID="Label2" CssClass="TextLabel" runat="server" Text="Đơn hàng (ngày):" />
	</div>
	<div  class="DivTextBox">
		<asp:TextBox ID="txtOrderDate" CssClass="TextBox" runat="server" Enabled="false" Text="" /> <asp:CheckBox id="chkEditDelivery" runat="server" Checked="false"  Text=" Sửa"/>
        
	</div>
	</div>
    
   
    <asp:CustomValidator ID="CustomValidator2" runat="server"   
                    ErrorMessage="Số lượng sản phẩm phải lớn hơn 0." 
                    ClientValidationFunction="CheckValueFiled" 
                    Display="None" />                               
</div> 
<div style="clear: both">
<br />
</div>
    <!-- Phần thêm chi tiết -->
<div class="DivRow">
    <fieldset style="border: 1px solid #B5CCE3; width: 96%">
            <legend><span id="clxp" style="cursor: pointer">
                <img id="imgshowhide" alt="" src="../../images/arrow_showless.gif" />Chi tiết đơn hàng</span></legend>
        <div id="search" class="BoxField">
            <div class="form" id="form">
                <div class="SubjectTitle">                       
                    <div class="DivTextBox" >
                        <div runat="server" id="divChoices">
                            <table id='tableChoices' width="92%">
                                <tr id='pRow'>
                                    <td width='20px' class='tdLabelT'>
                                        <b>STT</b>
                                    </td>
                                    <td width='150px'>
                                        <b>Mã Sản phẩm</b>
                                    </td>
                                    <td width='300px' >
                                        <b>Tên Sản phẩm</b>
                                    </td>
                                    <td width='70px' class='tdLabelT'>
                                        <b>Số lượng</b>
                                    </td>

                                    <td width='70px' nowrap ="nowrap">&nbsp;</td>
                                </tr>                        
                            </table>
                        </div>
                        <input type="button" onclick="addFormField();return false;" value="Thêm" class="btn"/>
                    </div>
	            </div>
                <div class="DivRow">
                    <center>
                        <div class="DivRow">
                            <input type="button" id="btnSave" value="Lưu" class="btn"  />
                            &nbsp;<asp:Button ID="btnCancel" CausesValidation="false" runat="server" Text=" Hủy " CssClass="btn" />
                           
                        </div>
                    </center>
                </div>
            </div>
        </div>
    </fieldset>
</div>
   
<div style="display: none">
    <asp:HiddenField runat="server" ID="hidRowIndex" Value="0" /><!-- by default there will be two inputs available to insert choices -->
    <asp:HyperLink ID = "hplShowProduct" runat="server" CssClass = "thickbox" NavigateUrl = "~/Page/Product/Popup.aspx?keepThis=true&TB_iframe=true&height=420&width=500&modal=true"></asp:HyperLink>
</div>
<div style="display: none">
            <asp:Button ID="btnSaveOrderDetail" runat="server" Text="" CssClass="btn" />
            <input type="text" id="curId"  />
            <input type="text" id="OriginalDeliveryDate" class="TextBox" />
            <asp:HiddenField ID="hidID" Value="0" runat="server" />
            <asp:HiddenField ID="hidSafeOffice" Value="" runat="server" />            
            <asp:TextBox ID="txtmaterialCode" Text="" runat="server" />
            <asp:HiddenField ID="hidOrderId" Value="" runat="server" />
            <asp:HiddenField ID="hidSale_Unit" Value="2" runat="server" /><!-- 0:PCS, 1:CTN 2: All -->
            <asp:TextBox ID = "txtCustomer" runat="server" Text = ""></asp:TextBox>
            
            <asp:TextBox ID = "txtGrossAmount" runat="server" Text = "0"></asp:TextBox>
        </div>
</ContentTemplate>
</asp:UpdatePanel>